import axios from 'axios'
const api = url => {
  if (process.env.NODE_ENV === 'development') {
    return '/api' + url
  } else {
    return 'url' + url
  }
}
const token = null

//  fromData
const reqData = (method, url, params) => {
  return axios({
    method: method,
    url: api(url),
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      openid: token
    },
    data: params,
    traditional: true,
    transformRequest: [
      function (data) {
        let ret = ''
        for (const it in data) {
          ret +=
            encodeURIComponent(it) +
            '=' +
            encodeURIComponent(data[it]) +
            '&'
        }
        return ret
      }
    ]
  })
}
// JSON
const reqJson = (method, url, params) => {
  return axios({
    method: method,
    url: api(url),
    headers: {
      'Content-Type': 'application/json',
      openid: token
    },
    data: params,
    traditional: true
  })
}
// 接口响应
axios.interceptors.response.use(
  response => {
    if (response.data.code === 200) {
      return Promise.resolve(response)
    } else {
      alert('error')
      return Promise.reject(response)
    }
  }
)
export {
  reqData,
  reqJson
}
